package com.kk.xhr.admin.biz.impl;

import com.kk.xhr.admin.biz.IRoleBizService;
import com.kk.xhr.admin.controller.request.RoleAddRequest;
import com.kk.xhr.admin.controller.request.RoleModifyRequest;
import com.kk.xhr.admin.controller.vo.RoleVO;
import com.kk.xhr.common.Constants;
import com.kk.xhr.common.ErrorCodeEnum;
import com.kk.xhr.common.exception.BusinessException;
import com.kk.xhr.common.pojo.BinaryEnum;
import com.kk.xhr.model.dto.PageDto;
import com.kk.xhr.model.entity.Role;
import com.kk.xhr.model.service.IPermissionService;
import com.kk.xhr.model.service.IRoleService;
import com.kk.xhr.web.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 角色biz服务接口实现
 *
 * @author kkmystery
 * @version 1.0 2021/3/12
 * @since 1.0.0
 */
@Service
@RequiredArgsConstructor
public class RoleBizServiceImpl implements IRoleBizService {
    private final IRoleService roleService;
    private final IPermissionService permissionService;

    @Override
    public PageVO<RoleVO> query() {
        PageDto<Role> dtos = roleService.query();
        if (0 == dtos.getTotal()) {
            return PageVO.empty();
        }
        return PageVO.fromDTO(dtos, dto -> RoleVO.builder()
            .id(dto.getId())
            .name(dto.getName())
            .nameZh(dto.getNameZh())
            .order(dto.getOrder())
            .status(BinaryEnum.from(dto.getStatus()))
            .build());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean modify(Long id, RoleModifyRequest request) {
        return roleService.modify(id, request.getName(), request.getNameZh(), request.getOrder());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modify(Long id, BinaryEnum status) {
        if (Constants.NOT_DELETE_ROLE_SET.contains(id)) {
            throw new BusinessException(ErrorCodeEnum.ROLE_NOT_ALLOW_DELETE);
        }
        // 删除对应的权限
        permissionService.deletePermissionByRoleId(id);
        return roleService.modifyStatus(id, status);
    }

    @Override
    public Long add(RoleAddRequest request) {
        return roleService.add(new Role()
            .withName(request.getName())
            .withNameZh(request.getNameZh())
            .withOrder(request.getOrder()));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addUserRole(Long userId, List<Long> roleIds) {
        roleService.deleteUserRole(userId);
        if (roleIds.isEmpty()) {
            return;
        }
        roleService.addUserRole(userId, roleIds);
    }
}
